﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using WHLRDF.ORM;
using WHLRDF.Application.Model;
namespace WHLRDF.Application.BLL
{
    public class SerialRuleService : SerivceBase, ISerialRuleService
    {
        #region 属性
        public const string SerialRule_No_Rule = "0004";
        public readonly object locked = new object();
      
        public const string SerialRule_Cache_Key = "SerialRuleValue";
        /// <summary>
        /// 存储编号值
        /// </summary>
        public static Dictionary<string, Dictionary<string, int>> SerialRuleKeyValues { get; set; }
        #endregion
        #region 基本方法
        /// <summary>
        /// 查询所有
        /// </summary>
        public List<SerialRuleEntity> GetAll()
        {
            ICriterion criter = Expression.Eq(SerialRuleEntity.__IsDeleted, false);
            return this.Query<SerialRuleEntity>(criter).ToList();

        }
        /// <summary>
        /// 获取单个实例的方法
        /// <param name="id">object类型</param>
        /// </summary>
        public SerialRuleEntity GetById(string id)
        {
            return this.GetById<SerialRuleEntity>(id);

        }

        /// <summary>
        /// 保存方法
        /// <param name="entity">对象</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Save(SerialRuleEntity entity, ref string strError)
        {
            if (string.IsNullOrWhiteSpace(entity.SerialRuleId))
            {
                entity.SerialRuleId = this.CreateSerialNo(SerialRule_No_Rule, null, ref strError);
            }
            return this.SaveOrUpdate(entity);

        }
        /// <summary>
        /// 删除方法
        /// <param name="deleteKey">主键，如果字符串请将字符串列表用单引号将字符串用上,如（'aaa','bbb'）</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Delete(string deleteKey, ref string strError)
        {
            if (!string.IsNullOrEmpty(deleteKey))
            {
                return this.Delete<SerialRuleEntity>(deleteKey);
            }
            return true;
        }
        /// <summary>
        /// 分页查询方法
        /// <param name="grid">分页查询的相关参数</param>
        /// </summary>
        public LigerGrid ForGrid(LigerGrid ligerGrid)
        {
            ICriterion criter = Expression.Eq(SerialRuleEntity.__IsDeleted, false);
            if (!string.IsNullOrEmpty(ligerGrid.keyWord))
            {
                criter = Expression.And(criter,

                           Expression.Like(SerialRuleEntity.__Remark, ligerGrid.keyWord)
                           );
            }
            return this.Query<SerialRuleEntity>(ligerGrid, criter);
        }
        #endregion

        #region 扩展方法
        /// <summary>
        /// 获取编号方法
        /// </summary>
        /// <param name="serialRuleId">标识</param>
        /// <param name="tableName"></param>
        /// <param name="fieldName"></param>
        /// <param name="dataParams">参数</param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public string CreateSerialNo(string serialRuleId, Dictionary<string, string> dataParams, ref string strError)
        {
            string SerialNo = "";
            string SerialPrefix = "";//前缀
            string SerialSuffix = "";//后缀
           
            if (string.IsNullOrEmpty(serialRuleId))
            {
                return "";
            }
            lock (locked)
            {
                SerialRuleEntity entity = CacheService.GetOrCreate<SerialRuleEntity>(ConfigHelper.GetCacheModelKey(typeof(SerialRuleEntity), serialRuleId), () =>
                {
                    return this.GetById(serialRuleId);
                }, true);
                if (entity == null)
                {
                    return "";
                }
                if (dataParams != null && dataParams.Count > 0)
                {
                    foreach (var key in dataParams.Keys)
                    {
                        if (!string.IsNullOrEmpty(entity.SerialPrefix))
                        {
                            SerialPrefix = entity.SerialPrefix.Replace("【" + key + "】", dataParams[key]);
                        }
                        if (!string.IsNullOrEmpty(entity.SerialSuffix))
                        {
                            SerialSuffix = entity.SerialSuffix.Replace("【" + key + "】", dataParams[key]);
                        }
                    }
                }
                else
                {
                    SerialPrefix = entity.SerialPrefix;
                    SerialSuffix = entity.SerialSuffix;
                }
                SerialNo += entity.IsYear ? DateTime.Now.Year.ToString() : "";
                SerialNo += entity.IsMonth ? DateTime.Now.Month.ToString().PadLeft(2, '0') : "";
                SerialNo += entity.IsDay ? DateTime.Now.Day.ToString().PadLeft(2, '0') : "";
                SerialNo += entity.IsTime ? DateTime.Now.ToString("HHmmss") : "";
                SerialNo = SerialPrefix + SerialNo + SerialSuffix;
              
                
                string NewSerialNo = SerialNo;
                DataParameterCollection dbParameters = new DataParameterCollection(this.DbRepository);
                dbParameters.Add(new DataParameter("RuleId", entity.SerialRuleId));
                dbParameters.Add(new DataParameter("SerialNo", SerialNo));
                dbParameters.Add(new DataParameter("UserId", ApplicationEnvironments.DefaultSession.UserId));
                dbParameters.Add(new DataParameter("InitCount", entity.SerialCount));
                dbParameters.Add(new DataParameter("NewMaxCount",0,true,System.Data.DbType.Int32));
                var obj= this.ExecuteProcedure("PROC_GetRuleCode", dbParameters);
                if (obj >= 0)
                {
                    entity.SerialCount = Convert.ToInt32(dbParameters[4].Value.ToString());
                }
                else {
                    throw new Exception(entity.SerialCount + "生成编号失败，请检查原因");
                }
                if (entity.SerialCount <= 0)
                {
                    throw new Exception(entity.SerialCount+"生成编号失败，请检查原因");
                }
                return SerialNo + entity.SerialCount.ToString().PadLeft(entity.SerialLength, '0');
            }
        }

       

     
        #endregion

    }
}